package cn.gov.nblr.top.sso.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SoaEncrypt
{

	public SoaEncrypt()
	{
	}
	
	private static String formatDate(){
		Date date=new Date();
		//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.format(date);
	}
	
	//decrypt
	public static String decrypt(String message, String key) {
		try {
			BASE64Decoder base64Decoder = new BASE64Decoder();
			byte bytesrc[] = base64Decoder.decodeBuffer(message );
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			javax.crypto.SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
			cipher.init(2, secretKey, iv);
			byte retByte[] = cipher.doFinal(bytesrc);
			
			String encryptMessage = new String(retByte);
			encryptMessage = encryptMessage.substring(0,encryptMessage.length() - 19);
			return encryptMessage;
		} catch (Exception ex) {
			return null;
		}
	}
	
	//encrypt
	public static String encrypt(String message, String key) {
		try {
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			javax.crypto.SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
			cipher.init(1, secretKey, iv);
			byte encryptbyte[] = cipher.doFinal((message + formatDate()).getBytes());
			BASE64Encoder base64Encoder = new BASE64Encoder();
			
			return base64Encoder.encode(encryptbyte);
		} catch (Exception ex) {
			return null;
		}
	}
}
